package com.shanxin.boom.mall.web.controller.security;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hwx.framework.base.domain.User;
import com.hwx.framework.base.exception.ServiceException;
import com.hwx.framework.web.util.MemberUtil;

/**
 */
public class Realm extends AuthorizingRealm {

    private static Logger logger = LoggerFactory.getLogger(Realm.class);

    /**
     * 用户登录的认证方法
     * 
     * @param authcToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
            throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        String loginName = token.getUsername();
        String password = new String(token.getPassword());
        User user = new User();
        try {
            // user = managerService.login(loginName, password,
            // token.getHost());
        } catch (ServiceException e) {
            logger.error(e.getCode(), e);
            /**
             * 登录失败，清空session中的用户信息
             */
            MemberUtil.removeUserInfo();
            throw new AuthenticationException(e.getMsg());
        } catch (Exception e) {
            logger.error(">>Error in LoginService!", e);
            throw new AuthenticationException(e.getMessage());
        }
        /**
         * 登录成功，缓存用户信息
         */
        MemberUtil.updateCurrentUser(user);
        return new SimpleAuthenticationInfo(user.getLoginName(), password, getName());
    }

    /**
     * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
     * 
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        /**
         * 查询当前登录用户的权限缓存信息，如果没有，则需从数据库查询
         */
        String loginName = (String) principalCollection.fromRealm(getName()).iterator().next();
        Set<String> stringPermissions = new HashSet<String>();
        if (MemberUtil.getPermissionCache() == null) {
            List<String> permisList = new ArrayList<String>();
            if ("admin".equalsIgnoreCase(loginName)) {
                // 为系统超级管理员时，获取所有权限
                // permisList =
                // managerService.queryPermsCodeListByLoginName(null);
            } else {
                // permisList =
                // managerService.queryPermsCodeListByLoginName(loginName);
            }
            stringPermissions.addAll(permisList);
            /**
             * 查询出来的权限信息需缓存进session
             */
            MemberUtil.updatePermissionCache(stringPermissions);
        } else {
            stringPermissions = MemberUtil.getPermissionCache();
        }
        info.setStringPermissions(stringPermissions);
        return info;
    }

}